import pandas as pd
import numpy as np
url="http://lib.stat.cmu.edu/datasets/boston"
df=pd.read_csv(url,sep="\s+",skiprows=22,header=None)
data=np.hstack([df.values[::2,:],df.values[1::2,:2]])
target=df.values[1::2,2]
x=data
y=target
from sklearn.linear_model import LinearRegression,Ridge,Lasso
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
#分割数据集
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=1,test_size=0.3)
#建立模型
lr=LinearRegression()
rd=Ridge()
ls=Lasso()
models=[lr,rd,ls]
names=['Linear','Ridge','Lasso']
#开始循环训练
for model,name in zip(models,names):
    model.fit(x_train,y_train)
    score=model.score(x_test,y_test)
    print("%s模型的预测准确率为:%.5f"%(name,score))
scores=[]
alphas=[0.0001,0.0005,0.001,0.005,0.01,0.05,0.1,0.5,1,5,10,50]
for index,model in enumerate(models):
    scores.append([])
    for alpha in alphas:
        if index>0:
            model.alpha=alpha
        model.fit(x_train,y_train)
        scores[index].append(model.score(x_test,y_test))
fig=plt.figure(figsize=(10,7))
for i,name in enumerate(names):
    plt.subplot(2,2,i+1)
    plt.plot(range(len(alphas)),scores[i],'g-')
    plt.title(name)
    print('%s模型的最大预测准确率为:%.5f'%(name,max(scores[i])))
plt.show()



import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
gl = np.array([1,2,3,4,5,6,7,8,9,10])
pjgz = np.array([2000,2200,4900,3221,6834,10567,9566,15678,13644,15789])
X = gl.reshape(-1, 1)
y = pjgz
lr_model = LinearRegression()
lr_model.fit(X, y)
y_pred = lr_model.predict(X)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False 
plt.figure(figsize=(10, 6))
plt.scatter(gl, pjgz, color='blue', s=80, label='原始数据（工龄-平均工资）')
plt.plot(gl, y_pred, color='red', linewidth=2.5, label='线性拟合线')
plt.title('工龄与平均年龄之间的关系图', fontsize=16, fontweight='bold')
plt.xlabel('工龄/年', fontsize=12)
plt.ylabel('平均工资/元', fontsize=12)
plt.legend(fontsize=11)
plt.show()